import { Injectable } from '@angular/core';
import {
    HttpEvent, HttpInterceptor, HttpHandler, HttpRequest
} from '@angular/common/http';
import { Observable } from 'rxjs';
import { environment } from '../../../environments/environment';

/**
 *
 * 设置url拦截器 自动适配base url
 * @export
 * @class ApiInterceptor
 * @implements {HttpInterceptor}
 */
@Injectable()
export class UrlInterceptor implements HttpInterceptor {
    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        let baseUrl: string;
        if (environment.production) {
            baseUrl = '';
        } else {
            baseUrl = '/api'; // http://sd-amazon.9peak.net
        }
        const apiReq = req.clone({
            url: `${baseUrl}/${req.url}`,
        });
        return next.handle(apiReq);
    }
}
